package com.lvyou.ctrl;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.lvyou.entity.Goods;
import com.lvyou.entity.Orders;
import com.lvyou.entity.UserModel;
import com.lvyou.model.JsonResult;
import com.lvyou.service.GoodsSrv;
import com.lvyou.service.OrderSrv;
import com.lvyou.util.TurnPage;

@RestController
@RequestMapping("/order")
@CrossOrigin
public class OrderCtrl {
	
	@Resource(name="GoodsSrv")
	private GoodsSrv srv;
	
	@Resource(name="OrderSrv")
	private OrderSrv orderSrv;
	
	@RequestMapping("/check")
	public JsonResult check(String id) {
		JsonResult jr=new JsonResult();
		try {
			Goods goods=srv.showGoodsById(id);
			jr.setCode(0);
			jr.setData(goods);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			jr.setCode(100000);
			jr.setMsg("发生错误！");
		}
		return jr;
	}
	@PostMapping("submit")
	public JsonResult submit(String personNum,String contactName,String phone,String email,String goodsId) {
		JsonResult jr=new JsonResult();
		HttpServletRequest req=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		HttpSession session=req.getSession();
		UserModel um=(UserModel)session.getAttribute("userInfo");
		try {
			int personNumInt=Integer.parseInt(personNum);
			Orders order=new Orders();
			order.setPersonNum(personNumInt);
			order.setContactName(contactName);
			order.setPhone(phone);
			order.setEmail(email);
			order.setGoodsId(goodsId);
			order.setUserId(um.getId());
			
			orderSrv.add(order);
			
			jr.setCode(0);
			jr.setMsg("提交成功！");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			jr.setCode(100000);
			jr.setMsg("发生错误！");
		}
		
		
		
		return jr;
	}
	@RequestMapping("/queryList")
	public JsonResult queryList(TurnPage turnPage) {
		JsonResult jr=new JsonResult();
		HttpSession session=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getSession();
		UserModel um=(UserModel)session.getAttribute("userInfo");
		try {
			List list=orderSrv.queryList(1,um.getId(),turnPage);
			jr.setCode(0);
			jr.setData(list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			jr.setCode(10000);
			jr.setMsg("发生错误！");
		}
		return jr;
	}

}
